package cn.cnnic.uploadkit.handler.impl;

import java.util.Map;

import cn.cnnic.uploadkit.handler.FormHandler;
import static cn.cnnic.uploadkit.MultipartFormdataUtil.*;

public class TextHandler implements FormHandler {

	public int get(int index, StringBuilder buffer, byte[] data, String boundary, Map<String, String> contentParmeter, Map<String, Object> parameters) {
		StringBuilder str = new StringBuilder();
		String line = null;

		while (!isDataEnd(data, index, boundary)) {
			index = readLine(data, buffer, index);
			line = clearBuffer(buffer);

			if (!isNewSeparator(line, boundary)) {
				if (str.length() != 0) {
					str.append("\r\n");
				}
				str.append(line);
			} else {
				break;
			}
		}

		String name = contentParmeter.get("name");

		if (parameters.containsKey(name)) {
			Object obj = parameters.get(name);
			String[] values = null;

			if (obj instanceof String[]) {
				values = new String[((String[]) obj).length + 1];
				System.arraycopy(obj, 0, values, 0, ((String[]) obj).length);
			} else {
				values = new String[2];
				values[0] = (String) parameters.get(name);
			}
			values[values.length - 1] = str.toString();

			parameters.put(name, values);
		} else {
			parameters.put(name, str.toString());
		}

		return readLine(data, buffer, index);
	}

}
